<template>
  <el-dialog v-model="visible" :title="`${paramsProps.title}`" :destroy-on-close="true" width="580px" draggable append-to-body>
    <el-form
      ref="ruleFormRef"
      label-width="140px"
      label-suffix=" :"
      :rules="rules"
      :model="paramsProps.row"
      @submit.enter.prevent="handleSubmit"
    >
      <el-form-item label="上级公司" prop="pid">
        <el-tree-select
          v-model="paramsProps.row.pid"
          :data="parentMenus"
          check-strictly
          placeholder="请选择上级"
          :render-after-expand="false"
          clearable
          :default-expand-all="true"
          :props="treeProps"
          :disabled="isParentCompanyDisabled"
        />
      </el-form-item>
      <el-form-item :label="paramsProps.row.pid === 0 ? '公司名称' : '车队名称'" prop="name">
        <el-input
          :placeholder="paramsProps.row.pid === 0 ? '请填写公司名称' : '请填写车队名称'"
          v-model="paramsProps.row.name"
          clearable
        />
      </el-form-item>
      <el-form-item label="公司人员" prop="leaderIds">
        <el-tag class="user-item" v-for="tag in leaders" :key="tag.id" type="info" closable @close="removeUser(tag.id)">
          {{ tag.nickname }}
        </el-tag>
        <el-button @click="chooseUser(paramsProps.row)"> 选择人员 </el-button>
      </el-form-item>
      <!-- <el-form-item label="排班时间" prop="schedule_id">
        <el-tree-select
          v-model="paramsProps.row.schedule_id"
          :data="scheduleList"
          check-strictly
          placeholder="请选择时间"
          :render-after-expand="false"
          clearable
          :default-expand-all="true"
          :props="scheduleProps"
        />
      </el-form-item> -->
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="paramsProps.row.sort" :precision="0" :min="1" :max="999999" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="paramsProps.row.remark" placeholder="请填写备注" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>

  <DeptLeaderTransfer ref="deptLeaderTransferRef" v-model="selectLeaderIds" />
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { type ElForm, ElMessage } from 'element-plus';
import type { SysDeptLeader, SysDeptTree } from '@/api/types/system/dept';
import type { VehicleScheduleRow } from '@/api/types/vehicleschedule/vehicleSchedule';
import { getMenuTree1, getSysDeptLeaderApi, getSysDeptLeaderApi2 } from '@/api/modules/system/dept';
import { getVehicleScheduleListNopApi } from '@/api/modules/vehicleschedule/vehicleSchedule';
import { getUserinfo } from '@/api/modules/system/user'; // Import getUserinfo API
import type { UserInfo } from '@/api/types/system/user'; // Import UserInfo type
import DeptLeaderTransfer from '@/views/system/deptManage/components/DeptLeaderTransfer.vue';
import { useUserStore } from '@/stores/modules/user'; // Import user store

defineOptions({
  name: 'SysDeptForm'
});

const userStore = useUserStore(); // Initialize user store

const parentMenus = ref<SysDeptTree[]>([]);
const treeProps = {
  label: 'name',
  value: 'id'
};
const scheduleList = ref<VehicleScheduleRow[]>([]);
const scheduleProps = {
  label: 'title',
  value: 'id'
};
const deptLeaderTransferRef = ref<InstanceType<typeof DeptLeaderTransfer>>();
const allLeaders = ref<SysDeptLeader[]>([]);
const selectLeaderIds = ref<number[]>([]);
const leaders = computed(() => {
  return allLeaders.value.filter(item => selectLeaderIds.value.includes(item.id));
});

// Computed property to check if current user is of type "user"
const isUserTypeUser = computed(() => {
  return userStore.userType === 'user';
});

// Computed property for whether the parent company selection should be disabled
const isParentCompanyDisabled = computed(() => {
  return isUserTypeUser.value && paramsProps.value.title === '新增公司';
});

// Store current user's department ID
const currentUserDeptId = ref<number | null>(null);

// Watch for changes in user type and department
watch(isUserTypeUser, (newVal) => {
  if (newVal && paramsProps.value.title === '新增公司') {
    // If user type is "user" and we're adding a new company, set default parent company
    setDefaultParentCompany();
  }
});

// 接收父组件传过来的参数
const acceptParams = (params: View.DefaultParams) => {
  paramsProps.value = params;
  selectLeaderIds.value = paramsProps.value.row?.leaders || [];
  console.log('接收的参数:', params);
  console.log('初始化的选中负责人ID:', selectLeaderIds.value);
  visible.value = true;
  loadParentMenus();
  loadLeaderInfo();
  loadCurrentUserDept(); // Load current user's department info
  // If user type is "user" and we're adding a new company, set default parent company
  if (isUserTypeUser.value && params.title === '新增公司') {
    setDefaultParentCompany();
  }
};

const loadParentMenus = () => {
  getMenuTree1({ excludeNodeId: paramsProps.value.row?.id }).then(res => {
    parentMenus.value = res.data;
  });
  getVehicleScheduleListNopApi({}).then(res => {
    // 确保res.data是数组
    scheduleList.value = Array.isArray(res.data) ? res.data : [res.data];
  });
};

const loadLeaderInfo = () => {
  getSysDeptLeaderApi().then(res => {
    allLeaders.value = res.data.leaderInfoVOS;
  });
  // getSysDeptLeaderApi2().then(res => {
  //   allLeaders.value = res.data.leaderInfoVOS;
  //   console.log('加载的所有负责人数据:', allLeaders.value);
  //   console.log('当前选中的负责人ID:', selectLeaderIds.value);
  //   console.log('最终显示的负责人:', leaders.value);
  // });
};

// Load current user's department information
const loadCurrentUserDept = () => {
  getUserinfo().then(res => {
    const userInfo: UserInfo = res.data;
    console.log(userInfo);
    currentUserDeptId.value = userInfo.deptId || null;
    
    // If user type is "user" and we're adding a new company, set default parent company
    if (isUserTypeUser.value && paramsProps.value.title === '新增公司') {
      setDefaultParentCompany();
    }
  }).catch(error => {
    console.error('Failed to load user info:', error);
  });
};

const rules = reactive({
  name: [{ required: true, message: '请填写公司名称' }],
  pid: [{ required: true, message: '请选择上级公司' }]
});

const visible = ref(false);
const paramsProps = ref<View.DefaultParams>({
  title: '',
  row: {},
  api: undefined,
  getTableList: undefined
});

// 提交数据（新增/编辑）
const ruleFormRef = ref<InstanceType<typeof ElForm>>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      paramsProps.value.row.leaders = selectLeaderIds.value;
      await paramsProps.value.api!(paramsProps.value.row);
      ElMessage.success({ message: `${paramsProps.value.title}成功！` });
      paramsProps.value.getTableList!();
      visible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
// 选择人员
const chooseUser = (row = {}) => {
  const params = {
    title: '设置人员',
    row: row,
    api: undefined,
    //api: '',
    leaderList: allLeaders.value,
    selectIds: selectLeaderIds.value,
    callback: (selectedIds: number[]) => {
      // 更新选中的负责人ID
      selectLeaderIds.value = selectedIds;
      console.log('通过回调更新的选中负责人ID:', selectLeaderIds.value);
      console.log('更新后的显示负责人:', leaders.value);
    }
  };
  deptLeaderTransferRef.value?.acceptParams(params);
};

// 移除人员
const removeUser = (id: number) => {
  const index = selectLeaderIds.value.findIndex(item => item === id);
  if (index !== -1) {
    selectLeaderIds.value.splice(index, 1);
  }
};

// Function to set default parent company
const setDefaultParentCompany = () => {
  // Set the parent company to the current user's department
  if (currentUserDeptId.value !== null) {
    paramsProps.value.row.pid = currentUserDeptId.value;
  }
};

defineExpose({
  acceptParams
});
</script>
